<template>
	<template>
		<view class="app-nearby-map">
			<tmap
				:latitude="latitude"
				:longitude="longitude"
				:userLongitude="userLongitude"
				:userLatitude="userLatitude"
				:minScale="12"
				:scale="15"
				:maxScale="18"
				autoLocation
				layerStyle
				@mapLocationChange="handleMapLocationChange"
				@getMarkerArray="getMarkerArray"
				@updateLocation="handleUpdateLocation"
				@markerClick="handleMarkerClick"
			></tmap>
		</view>
	</template>
</template>

<script setup lang="ts">
import { ref, computed, nextTick } from 'vue';
import { debounce } from '@/common/utils';
import { getNearbyStoreList } from '@/common/request/api';
import type { NearbyStoreInfo } from '@/common/request/api';
import { useCurrentInstance } from '@/common/hooks';
import { defaultLatitude, defaultLongitude } from '@/common/utils/map/index';

const ctx = useCurrentInstance();

const latitude = ref(defaultLatitude);
const longitude = ref(defaultLongitude);
const userLatitude = ref(defaultLatitude);
const userLongitude = ref(defaultLongitude);

const storeList = ref<NearbyStoreInfo[]>([]);

const markers = computed(() =>
	storeList.value.map((item, index) => {
		const location = item.location?.split(',');
		return {
			latitude: Number(location[1]),
			longitude: Number(location[0]),
			id: index,
			iconPath: ctx.$fullLink(item.logo),
			width: 32,
			height: 32,
			alpha: 0.8,
			collision: 'marker',
			callout: {
				display: 'ALWAYS',
				content: item.name,
				fontSize: 11,
				padding: 6,
				borderRadius: 4,
				textAlign: 'center'
			}
		};
	})
);
const getData = async () => {
	const res = await getStoreList({
		pageSize: 100,
		pageNum: 1,
		ranges: 10000,
		location: {
			latitude: latitude.value,
			longitude: longitude.value
		}
	});
	storeList.value = res.data.rows;
};
const handleUpdateLocation = (
	res: {
		latitude: number;
		longitude: number;
	},
	cb: Function
) => {
	latitude.value = location.latitude;
	longitude.value = location.longitude;
	userLatitude.value = res.latitude;
	userLongitude.value = res.longitude;
	getData().finally(() => {
		cb();
	});
};
const handleMapLocationChange = debounce(function (
	location: {
		latitude: number;
		longitude: number;
	},
	cb: Function
) {
	latitude.value = location.latitude;
	longitude.value = location.longitude;
	getData()
		.then(() => {
			nextTick(() => {
				cb(true);
			});
		})
		.catch(() => {
			cb(false);
		});
}, 2000);
const getMarkerArray = (cb: Function) => {
	cb(markers.value, false);
};

const handleMarkerClick = (e: any) => {
	let storeId = '';
	// #ifdef MP-WEIXIN||MP-ALIPAY
	storeId = storeList.value[e.detail.markerId].id;
	// #endif
	// #ifndef MP-WEIXIN||MP-ALIPAY
	storeId = e;
	// #endif
	ctx.$goTo('/pages/nearby/store/info',  { id: storeId });
};
</script>

<style lang="scss" scoped>
@include appBem_b(nearby-map) {
	width: 100vw;
	height: 100vh;
}
</style>
